package cn.shopex.multiimagepreview.app;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.lang.ref.WeakReference;

import cn.shopex.multiimagepreview.R;

/**
 * Created by p on 2016/11/11.
 */
public class ProgressImageView extends RelativeLayout {
    private ImageViewOnClick mImageViewOnClick;
    private TouchImageView touchImageView;
    private WeakReference<TouchImageView> imageViewWeakReference;

    public ProgressImageView(Context context) {
        super(context);
        initializeViews(context, null);
    }

    public ProgressImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initializeViews(context, attrs);
    }

    private void initializeViews(Context context, AttributeSet attrs) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.fragment_image_view, this, true);
        touchImageView = (TouchImageView) findViewById(R.id.touch_img);
        imageViewWeakReference = new WeakReference<>(touchImageView);
    }

    public void setImageViewOnClick(ImageViewOnClick imageViewOnClick) {
        mImageViewOnClick = imageViewOnClick;
    }

    public interface ImageViewOnClick {
        void onImageClick(View v);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        touchImageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mImageViewOnClick.onImageClick(v);
            }
        });
    }

    public void load(String url, Fragment fragment) {
        ImageView target = imageViewWeakReference.get();
        Glide.with(fragment).load(url)
                .asBitmap()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .placeholder(R.drawable.image_loading)
                .error(R.drawable.image_failure)
                .thumbnail(0.1f)
                .fitCenter() // needs explicit transformation, because we're using a custom target
                .into(target);

    }
    }
